package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_me

import android.content.Intent
import android.net.Uri
import android.view.View
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_language.BpLanguageActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.feedback.FeedBackActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.BpGuideCamareDialog
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.databinding.MeFragmentBgBinding
import com.bp.hearthealth.pulse.lnapps.notification.NotificationControlManager
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.Toaster
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Timer
import java.util.TimerTask

class BpMeFragment : BpBaseFragment<MeFragmentBgBinding>() {

    private var nativeAd: NativeAd? = null
    private val viewModel: BpMeViewModel by viewModel()
    private val timer = Timer()

    override fun loadDataOnce() {
        super.loadDataOnce()
        binding.apply {
            lifecycleOwner = this@BpMeFragment
            viewModel = this@BpMeFragment.viewModel
            initData()
        }
        startStopListener()
    }

    private fun startStopListener() {
        timer.schedule(object : TimerTask() {
            override fun run() {
                //首次加载超过3秒不显示
                AdMobNativeAdManager.setNativeAdListener(null)
            }
        }, 3000)
    }


    override fun onResume() {
        super.onResume()
//        loadNativeAd()
        val openNotification = NotificationControlManager.isOpenNotification()
        if (openNotification) {
            binding.includeNotification.ivRightIcon.setImageResource(R.mipmap.me_notif_on_bp)
        } else {
            binding.includeNotification.ivRightIcon.setImageResource(R.mipmap.me_notif_off_bp)
        }
    }

    override fun onVisible() {
//        loadNativeAd()
    }

    private fun initData() {
        BpLiveDataBus.with<Boolean>(AdsSwitch.adAppControl).observe(this) {
            binding.nativeAdContainer.visibility = View.GONE
            AdMobNativeAdManager.release()
        }
        binding.apply {
            tvLogin.throttleClick {
//                    NotificationControlManager.notifyCustomNotification(
//                        "0",
//                        Uri.parse("https://tucdn.wpon.cn/2024/04/16/902976654b8ff.png"),
//                        "通知内容"
//                    )
            }
            tvUpgrade.throttleClick { Toaster.show(UIHelperBp.getString(R.string._coming_soon_str)) }
            includeNotification.apply {
                tvItemText.text = getString(R.string._notification_str)
                ivIcon.setImageResource(R.mipmap.me_notif_icon_bp)
                ivRightIcon.throttleClick {
                    val openNotification = NotificationControlManager.isOpenNotification()
                    if (openNotification) {
                        NotificationControlManager.openNotificationInSys()
                    } else {
                        val permissionDialog = BpGuideCamareDialog(activity)
                        permissionDialog.showDialog(UIHelperBp.getString(R.string._dialog_notification_permission_str))
                        permissionDialog.setOnBtnClickLisener(object :
                            BpGuideCamareDialog.OnBtnClickListener {
                            override fun onBtnClick() {
                                NotificationControlManager.openNotificationInSys()
                            }
                        })
                    }
                }
            }

            includeRewards.tvItemText.apply {
                throttleClick {
                    Toaster.show(UIHelperBp.getString(R.string._coming_soon_str))
                }
            }

            includeLanguage.ivIcon.setImageResource(R.mipmap.me_language_icon_bp)
            includeLanguage.tvItemText.apply {
                text = getString(R.string._language_str)
                throttleClick {
                    val intent = Intent(activity, BpLanguageActivity::class.java)
                    intent.putExtra(Constants.LANGUAGE_FORM, Constants.LANGUAGE_FORM)
                    startActivity(intent)
                }
            }

            includeExportFile.ivIcon.setImageResource(R.mipmap.me_export_file_icon_bp)
            includeExportFile.tvItemText.apply {
                text = getString(R.string._export_as_file_str)
                throttleClick {
                    Toaster.show(UIHelperBp.getString(R.string._coming_soon_str))
                }
            }

            includeProfile.ivIcon.setImageResource(R.mipmap.me_profile_icon_bp)
            includeProfile.tvItemText.apply {
                text = getString(R.string._profile_str)
                throttleClick {
                    Toaster.show(UIHelperBp.getString(R.string._coming_soon_str))
                }
            }

            includeFeedback.ivIcon.setImageResource(R.mipmap.me_feedback_icon_bp)
            includeFeedback.tvItemText.apply {
                text = getString(R.string._feedback_str)
                throttleClick {
                    startActivity(Intent(activity, FeedBackActivity::class.java))
                }
            }

            includeRateUs.ivIcon.setImageResource(R.mipmap.me_rate_us_icon_bp)
            includeRateUs.tvItemText.apply {
                text = getString(R.string._rate_us_str)
                throttleClick {
                    Toaster.show(UIHelperBp.getString(R.string._coming_soon_str))
                }
            }

            includePrivacy.ivIcon.setImageResource(R.mipmap.me_privacy_icon_bp)
            includePrivacy.tvItemText.apply {
                text = getString(R.string._privacy_str)
                throttleClick {
                    openLink(Constants.PORIVACY_POLICY)
                }
            }

            includeTerms.ivIcon.setImageResource(R.mipmap.me_terms_icon_bp)
            includeTerms.tvItemText.apply {
                text = getString(R.string._terms_str)
                throttleClick {
                    openLink(Constants.TERMS)
                }
            }
        }
    }

    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                LogUtil.i("BpMeFragment onAdLoaded 回调")
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_me_show")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            LogUtil.i("BpMeFragment 设置广告显示")
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    fun openLink(content: String?) {
        try {
            val issuesUrl = Uri.parse(content)
            val intent = Intent(Intent.ACTION_VIEW, issuesUrl)
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(binding.toolbar).init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }
}